package demo15;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 综合练习_全排列II
 * https://leetcode.cn/problems/7p8L0Z/description/
 */
class Solution1 {
    List<List<Integer>> ret = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] check;
    Set<ArrayList> set = new HashSet<>();
    int len;
    public List<List<Integer>> permuteUnique(int[] nums) {
        len = nums.length;

        check = new boolean[len];
        dfs(nums);
        return ret;
    }

    private void dfs(int[] nums) {
        if(len == path.size() && !set.contains(path)) {
            ret.add(new ArrayList<>(path));
            set.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < len; i++) {
            if(!check[i]) {
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                // 恢复现场
                path.remove(path.size() -1);
                check[i] = false;
            }
        }
    }
}